<template>
  <div>
    <!-- <el-form :model="form" label-width="auto">
      <el-form-item label="Activity zone">
        <el-select v-model="form.region" placeholder="please select your zone">
          <el-option label="Zone one" value="shanghai" />
          <el-option label="Zone two" value="beijing" />
        </el-select>
      </el-form-item>
      <el-form-item label="Activity time">
        <el-col :span="11">
          <el-date-picker
            v-model="form.date1"
            type="date"
            placeholder="Pick a date"
            style="width: 100%"
          />
        </el-col>
      </el-form-item>
      <el-form-item label="Resources">
        <el-radio-group v-model="form.resource">
          <el-radio value="Sponsor">Sponsor</el-radio>
          <el-radio value="Venue">Venue</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="Activity form">
        <el-input v-model="form.desc" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">Create</el-button>
        <el-button>Cancel</el-button>
      </el-form-item>
    </el-form> -->
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
      class="demo-ruleForm"
      :size="formSize"
      status-icon
      style="width: 1100px; margin: auto"
    >
      <el-row :gutter="24">
        <el-col :span="12" :offset="0"
          ><el-form-item label="销售单号:" prop="SalesOrderNumber">
            <el-input
              v-model="ruleForm.SalesOrderNumber"
              :disabled="isInputDisabled"
            ></el-input>
            <el-checkbox-group
              v-model="checkedType"
              @change="handleCheckboxChange"
            >
              <el-checkbox label="type">系统编号</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
          <el-form-item label="销售日期" prop="SalesDate">
            <el-date-picker
              v-model="ruleForm.SalesDate"
              type="date"
              placeholder="请选择日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="联系人:" prop="LinkMan">
            <el-input v-model.number="ruleForm.LinkMan" />
          </el-form-item>
          <el-form-item label="联系电话:" prop="ContactNumber">
            <el-input v-model="ruleForm.ContactNumber" />
          </el-form-item>
          <el-form-item label="备注" prop="Remark">
            <el-input v-model="ruleForm.Remark" type="textarea" />
          </el-form-item>
        </el-col>
        <el-col :span="12" :offset="0">
          <el-form-item label="客户名称" prop="CustomerName">
            <el-select
              v-model="ruleForm.ClientId"
              placeholder="请选择"
              style="width: 240px"
            >
              <el-option
                v-for="item in CilentList"
                :key="item.ClientId"
                :label="item.ClientName"
                :value="item.ClientId"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="联系方式:" prop="ContactInformation">
            <el-input v-model="ruleForm.ContactInformation" />
          </el-form-item>
          <el-form-item label="收货地址:" prop="DestinationOfDelivery">
            <el-input v-model="ruleForm.DestinationOfDelivery" /> </el-form-item
        ></el-col>
      </el-row>
      <el-dialog v-model="dialogVisible" title="选择产品" width="1200">
        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="产品名称">
            <el-input
              v-model="formInline.product_Name"
              placeholder="请输入产品名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="规格型号">
            <el-input
              v-model="formInline.model_Number"
              placeholder="请输入规格型号"
              clearable
            />
          </el-form-item>
          <el-form-item label="品牌">
            <el-input
              v-model="formInline.brand"
              placeholder="请输入品牌"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="fetchData">查询</el-button>
          </el-form-item>
        </el-form>

        <el-table
          :data="tableData"
          border
          style="width: 100%"
          ref="multipleTableRef"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column label="产品编号" align="center">
            <!-- 使用 row.Product_Code 显示产品编号 -->
            <template v-slot="slot">
              {{ slot.row.Product_Code }}
            </template>
          </el-table-column>
          <el-table-column
            prop="Product_Name"
            label="产品名称"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="Model_Number"
            label="规格型号"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="Brand"
            label="品牌"
            align="center"
          ></el-table-column>
          <el-table-column label="单位" align="center">
            <template v-slot="slot">
              <!-- 使用 row.UnitName 显示单位名称 -->
              {{ slot.row.Unit_Id }}
            </template>
          </el-table-column>
          <el-table-column label="物料类别" align="center">
            <template v-slot="slot">
              <!-- 使用 row.TypeName 显示物料类别名称 -->
              {{ slot.row.Product_Category_Id }}
            </template>
          </el-table-column>
          <el-table-column label="物料属性" align="center">
            <template v-slot="slot">
              <!-- 使用 row.AttName 显示物料属性名称 -->
              {{ slot.row.Product_Attributes_Id }}
            </template>
          </el-table-column>
          <el-table-column prop="Unit_Price" label="销售单价" align="center">
            <template v-slot="slot">
              <!-- 使用 row.UnitPrice 显示销售单价 -->
              {{ slot.row.Unit_Price.toFixed(2) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="Minimum_Stock_Quantity"
            label="最小库存数"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="Maximum_Stock_Quantity"
            label="最大库存数"
            align="center"
          ></el-table-column>
          <el-table-column
            prop="Product_Expiry_Date"
            label="产品有效期"
            align="center"
          >
            <template v-slot="slot">
              <!-- 使用 row.MatDate 显示日期 -->
              {{ slot.row.Product_Expiry_Date.substr(0, 10) }}
            </template>
          </el-table-column>
          <el-table-column
            prop="Alert_Days"
            label="报警天数"
            align="center"
          ></el-table-column>
          <el-table-column prop="Status" label="状态" align="center">
            <template v-slot="slot">
              <!-- 使用 row.TypeName 显示物料类别名称 -->
              <span v-if="slot.row.Status == 1">启用</span>
              <span v-else>禁用</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="Remarks"
            label="备注"
            align="center"
          ></el-table-column>
          <el-table-column prop="Product_Image" label="产品图片" align="center">
            <template v-slot="slot">
              <img
                :src="
                  'http://10.31.59.10:8085/api/PIC/' + slot.row.Product_Image
                "
                style="width: 55px; height: 55px"
              />
            </template>
          </el-table-column>
        </el-table>

        <template #footer>
          <div class="dialog-footer">
            <el-button>取消</el-button>
            <el-button type="primary" @click="ProcessAdd"> 确定 </el-button>
          </div>
        </template>
        <table style="margin: auto">
          <tr>
            <td>
              <el-pagination
                v-model:current-page="page"
                v-model:page-size="size"
                :page-sizes="[10, 20, 30, 40]"
                :small="small"
                :disabled="disabled"
                :background="background"
                layout="total, sizes, prev, pager, next, jumper"
                :total="totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </td>
          </tr>
        </table>
      </el-dialog>
      <span>产品明细</span>
      <br />
      <br />
      <el-button type="primary" @click="ProcessAddess()">添加</el-button>
      <el-button>移除</el-button>
      <br />
      <br />
      <el-table
        :data="PressApplist"
        border
        style="width: 100%"
        ref="multipleTableRef"
        @selection-change="ProcessflowInfo"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column label="产品编号" align="center">
          <!-- 使用 row.Product_Code 显示产品编号 -->
          <template v-slot="slot">
            {{ slot.row.Product_Code }}
          </template>
        </el-table-column>
        <el-table-column
          prop="Product_Name"
          label="产品名称"
          align="center"
        ></el-table-column>
        <el-table-column
          prop="Model_Number"
          label="规格型号"
          align="center"
        ></el-table-column>

        <el-table-column label="单位" align="center">
          <template v-slot="slot">
            <!-- 使用 row.UnitName 显示单位名称 -->
            {{ slot.row.UnitName }}
          </template>
        </el-table-column>
        <el-table-column label="物料类别" align="center">
          <template v-slot="slot">
            <!-- 使用 row.TypeName 显示物料类别名称 -->
            {{ slot.row.Product_Category_Id }}
          </template>
        </el-table-column>
        <el-table-column label="销售单价" align="center">
          <template v-slot="slot">
            <!-- 使用 row.UnitPrice 显示销售单价 -->
            <el-input v-model="slot.row.Unit_Price"></el-input>
            <!-- {{ slot.row.Unit_Price.toFixed(2) }} -->
          </template>
        </el-table-column>
        <el-table-column label="产品有效期" align="center">
          <template v-slot="slot">
            <!-- 使用 row.MatDate 显示日期 -->
            <!-- {{ slot.row.Product_Expiry_Date.substr(0, 10) }} -->
            <el-date-picker
              v-model="slot.row.Product_Expiry_Date"
              type="date"
              label="Pick a date"
              placeholder="请选择日期"
              style="width: 100%"
            />
          </template>
        </el-table-column>
        <el-table-column label="备注" align="center">
          <template v-slot="slot">
            <!-- 使用 row.MatDate 显示日期 -->
            <!-- {{ slot.row.Product_Expiry_Date.substr(0, 10) }} -->
            <el-input v-model="slot.row.Remarks"></el-input>
          </template>
        </el-table-column>
      </el-table>
      <br />
      <br />
      <el-button type="primary" @click="submitForm(ruleFormRef)"
        >确定</el-button
      >
      <el-button>移除</el-button>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import { ElMessage, FormInstance, FormRules } from "element-plus";
import axios from "axios";
import { json } from "stream/consumers";
import { tr } from "element-plus/es/locale";
import router from "@/router";
const tableData = ref([]);
const totalCount = ref(0);
const page = ref(1);
const size = ref(10);
const small = ref(true);
const disabled = ref(false);
const background = ref(true);
const units = ref([]); // 单位下拉列表数据
const materialTypes = ref([]); // 物料类别下拉列表数据
const materialProperties = ref([]); // 物料属性下拉列表数据
//const multipleSelection = ref<RuleForm[]>([]);
const CilentList = ref([]);
const CilentListsss = ref("");
const ProductList = ref(false);
const ProcesspIndex = ref(false);
const ProcessInfo = ref({
  Id: "",
});
const formInline = reactive({
  // 表单数据
  product_Name: "",
  model_Number: "",
  brand: "",
});
const Processflow = ref([]);
const ProcessflowInfo = (sel) => {
  Processflow.value = sel;
};
const PressApplist = ref();
const ProcessAdd = () => {
  window.localStorage.setItem("AddInfo", JSON.stringify(tableData.value));
  PressApplist.value = JSON.parse(window.localStorage.getItem("AddInfo"));
  dialogVisible.value = false;
};
// const GetProduct = () => {
//   axios.get("").then((res) => {
//     ProductList.value = res.data;
//   });
// };
const handleSizeChange = (val) => {
  size.value = val;
  fetchData();
};
const handleCurrentChange = (val) => {
  page.value = val;
  fetchData();
};
const fetchData = async () => {
  try {
    const response = await axios.get(
      `Product/GetUserListByKeyword?page=${page.value}&size=${size.value}&product_Name=${formInline.product_Name}&model_Number=${formInline.model_Number}&brand=${formInline.brand}`
    );
    if (response.data.Data && response.data.Data.length > 0) {
      tableData.value = response.data.Data;
      totalCount.value = response.data.TotalCount;
    } else {
      tableData.value = [];
      totalCount.value = 0;
    }
  } catch (error) {
    console.error("Error fetching data:", error);
  }
};
interface RuleForm {
  SalesOrderNumber: string;
  CustomerName: string;
  SalesDate: string;
  ContactInformation: string;
  LinkMan: string;
  DestinationOfDelivery: string;
  ContactNumber: string;
  Remark: string;
  ClientId: string;
  sale_ProductDTO: [];
}
interface User {
  Product_Code: string;
  Product_Name: string;
  Model_Number: string;
  Brand: string;
  Unit_Id: string;
  Product_Category_Id: string;
  Unit_Price: string;
  Minimum_Stock_Quantity: string;
  Maximum_Stock_Quantity: string;
  Product_Expiry_Date: string;
  Alert_Days: string;
  Status: string;
  Product_Image: string;
  sale_ProductDTO: string;
}
const formSize = ref("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  SalesOrderNumber: "",
  CustomerName: "",
  SalesDate: "",
  ContactInformation: "",
  LinkMan: "",
  DestinationOfDelivery: "",
  ContactNumber: "",
  Remark: "",
  ClientId: "",
  sale_ProductDTO: [],
});
const dialogVisible = ref(false);
const Product = ref([]);
const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<User[]>([]);

const handleSelectionChange = (val: User[]) => {
  multipleSelection.value = val;
};

// const tableData: User[] = [];
const GetCilentList = () => {
  axios.get("Sale/GetClients").then((res) => {
    CilentList.value = res.data;
  });
};
const rules = reactive<FormRules<RuleForm>>({
  SalesOrderNumber: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { min: 3, max: 5, message: "长度为3到5", trigger: "blur" },
  ],
  ClientId: [
    {
      message: "请选择客户",
      trigger: "change",
    },
  ],
  LinkMan: [
    {
      type: "integer",
      required: true,
      message: "请输入联系人,且联系人必须为整数！",
      trigger: "blur",
    },
    { pattern: /^1[3-9]\d{9}$/, message: "联系人格式不正确" },
  ],
  ContactNumber: [
    { required: true, message: "请输入联系电话", trigger: "blur" },
  ],
  Remark: [{ required: true, message: "请输入备注", trigger: "blur" }],
  ContactInformation: [
    { required: true, message: "请输入联系方式", trigger: "blur" },
  ],
  DestinationOfDelivery: [
    { required: true, message: "请输入收货地址", trigger: "blur" },
  ],
  SalesDate: [
    {
      type: "date",
      required: true,
      message: "请选择日期",
      trigger: "change",
    },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (PressApplist.value.length == null) {
        ElMessage.error("请选择一条数据");
        return;
      }
      ruleForm.sale_ProductDTO = tableData.value;
      axios.post("Sale/AddSale", ruleForm).then((res) => {
        if (res.data.Code == 200) {
          ElMessage.success(res.data.Message);
          router.push(`/UserList/saleshow`);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const checkedType = ref([]);
const inputValue = ref("");
const isInputDisabled = ref(false);

const handleCheckboxChange = (checkedValues) => {
  if (checkedValues.includes("type")) {
    isInputDisabled.value = true;
    generateCode();
  } else {
    isInputDisabled.value = false;
    inputValue.value = "";
  }
};
const ProcessAddess = () => {
  page.value = 1;
  size.value = 1;
  fetchData();
  dialogVisible.value = true;
};
const generateCode = () => {
  let result = "";
  const characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  const charactersLength = characters.length;

  for (let i = 0; i < 25; i++) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
  }

  inputValue.value = result;
};
fetchData();
GetCilentList();
</script>

<style>
</style>
